<template>
  <div class="dialog-form">
    <el-dialog
      v-if="modelVisible"
      :title="id ? '修改' : '新增'"
      :visible.sync="modelVisible"
      @close="clear"
    >
      <modal-form
        :formData="dialogData"
        :isFlex="isFlex"
        ref="formData"
      ></modal-form>
      <el-button type="primary" @click="update">{{
        id ? "修改" : "确认"
      }}</el-button
      ><el-button @click="clear">清除</el-button>
    </el-dialog>
  </div>
</template>

<script>
import ModalForm from "@/components/modal-form.vue";

export default {
  name: "filter-form",
  components: {
    ModalForm,
  },
  data() {
    return {
      modelVisible: false,
    };
  },
  props: {
    dialogData: {
      type: Array,
      default: undefined,
    },
    dialogVisible: {
      type: Boolean,
      default: undefined,
    },
    id: {
      type: Number,
      default: undefined,
    },
    isFlex: {
      type: Boolean,
      default: true,
    },
  },
  watch: {
    dialogVisible: {
      immediate: true,
      deep: true,
      handler(val) {
        this.modelVisible = val;
      },
    },
  },
  beforeDestroy() {
    this.$emit("close-dialog");
  },

  methods: {
    async update() {
      let flag = await this.$refs.formData.justify();
      //如果子组件校验方法返回ture，则接着进行其他操作，返回false则提示用户
      if (flag) {
        if (this.id) {
          this.$emit("update-dialog", "update", {
            ...this.$refs.formData.formDataObject,
            ...{ id: this.id },
          });
        } else {
          this.$emit(
            "update-dialog",
            "add",
            this.$refs.formData.formDataObject
          );
        }
      }
    },
    clear() {
      this.$refs.formData.remove();
      this.$emit("close-dialog");
    },
  },
};
</script>
<style lang="less" scoped></style>
